<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          @click="handleSearchList()"
          type="primary"
          size="small"
        >
          查询结果
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="small"
          label-width="140px"
        >
          <el-form-item label="输入搜索：">
            <el-input
              style="width: 203px"
              v-model="listQuery.title"
              placeholder="视频标题"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="视频ID：">
            <el-input
              style="width: 203px"
              v-model="listQuery.uvid"
              placeholder="视频ID"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="视频分区：">
            <el-cascader
              clearable
              v-model="selectPartitionValue"
              :options="partitionOptions"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="视频作者：">
            <el-input
              style="width: 203px"
              v-model="listQuery.userNickname"
              placeholder="视频作者"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="text" size="small" @click="fixTime"
        >修复视频时长</el-button
      >
      <el-button type="text" size="small" @click="fixProfile"
        >修复视频统计信息</el-button
      >
      <el-button type="text" size="small" @click="fixUvid"
        >修复视频唯一标识</el-button
      >
    </el-card>
    <div class="table-container">
      <el-tabs v-model="statusTab" type="card" @tab-click="handleClickTabs">
        <el-tab-pane
          :label="'全部(' + countMap.allCount + ')'"
          name="-1"
        ></el-tab-pane>
        <el-tab-pane
          :label="'已下架(' + countMap.offTheShelfCount + ')'"
          name="40"
        ></el-tab-pane>
        <el-tab-pane
          :label="'审核通过(' + countMap.approvedCount + ')'"
          name="30"
        ></el-tab-pane>
        <el-tab-pane
          :label="'待审核(先审后发)(' + countMap.reviewIssueCount + ')'"
          name="20"
        ></el-tab-pane>
        <el-tab-pane
          :label="'待审核(先发后审)(' + countMap.issueReviewCount + ')'"
          name="10"
        ></el-tab-pane>
        <el-tab-pane
          :label="'审核未通过(' + countMap.notPassedCount + ')'"
          name="0"
        ></el-tab-pane>
      </el-tabs>
      <el-table
        ref="videoTable"
        :data="list"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        v-loading="listLoading"
        border
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="唯一标识" width="180" align="center">
          <template slot-scope="scope">{{ scope.row.uvid }}</template>
        </el-table-column>
        <el-table-column label="视频封面" width="100" align="center">
          <template slot-scope="scope"
            ><el-image
              style="height: 80px"
              fit="contain"
              :src="scope.row.cover"
              :preview-src-list="[scope.row.cover]"
            />
          </template>
        </el-table-column>
        <el-table-column label="视频标题" align="center">
          <template slot-scope="scope"
            ><b>{{ scope.row.title }}</b></template
          >
        </el-table-column>
        <el-table-column label="视频时长" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.duration }}</template>
        </el-table-column>
        <el-table-column label="视频作者" width="80" align="center">
          <template slot-scope="scope"> {{ scope.row.userNickname }}</template>
        </el-table-column>
        <el-table-column label="视频分区" width="100" align="center">
          <template slot-scope="scope"
            ><el-tag>{{ scope.row.partitionName }}</el-tag></template
          >
        </el-table-column>
        <el-table-column label="视频地址" width="80" align="center">
          <template slot-scope="scope"
            ><el-link
              type="primary"
              @click="handleViewVideo(scope.$index, scope.row)"
              >浏览视频</el-link
            ></template
          >
        </el-table-column>
        <el-table-column label="上传时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.uploadTime }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="110" align="center">
          <template slot-scope="scope">
            <p
              :class="
                scope.row.status === 30 ? 'success-status' : 'error-status'
              "
            >
              {{ scope.row.status | statusFilter }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <p>
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                :disabled="isEmpty(scope.row.source)"
                >编辑
              </el-button>
              <el-button
                size="mini"
                @click="handleSetPartition(scope.$index, scope.row)"
                >设置
              </el-button>
            </p>
            <p>
              <el-button
                size="mini"
                @click="handleVerify(scope.$index, scope.row)"
                >审核
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除
              </el-button>
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option
          v-for="item in operates"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchOperate()"
        type="primary"
        size="small"
      >
        确定
      </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[10, 15, 20, 50, 200]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
      >
      </el-pagination>
      <div style="height: 20px"></div>
    </div>
    <el-dialog
      :visible.sync="viewVideoDialogVisible"
      width="50%"
      center
      @close="handleViewDialogClose"
      :destroy-on-close="true"
    >
      <video-player :src="videoSrc"></video-player>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="verifyDialogVisible" width="30%">
      <el-form :model="verifyForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="verifyForm.verifyStatus" size="medium">
            <el-radio :label="40">下架</el-radio>
            <el-radio :label="30">通过</el-radio>
            <el-radio :label="0">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="verifyForm.detail"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleVerifySubmit" size="small"
          >确 定</el-button
        >
        <el-button @click="verifyDialogVisible = false" size="small"
          >取 消</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="设置分区"
      :visible.sync="setPartitionDialogVisible"
      width="30%"
    >
      <el-form :model="partitionForm" label-width="100px">
        <el-form-item label="视频分区：">
          <el-cascader
            clearable
            v-model="newPartitionValue"
            :options="partitionOptions"
          >
          </el-cascader>
        </el-form-item>
        <el-alert
          v-if="newPartitionValue"
          title="提示"
          type="info"
          :description="tip"
          show-icon
        >
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSetPartitionSubmit" size="small"
          >确 定</el-button
        >
        <el-button @click="setPartitionDialogVisible = false" size="small"
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchList,
  deleteVideo,
  getCounts,
  updateStatus,
  changePartition,
} from "@/api/video";
import { fetchListWithChildren } from "@/api/partition";
import { fixVideoUvid, fixVideoTime, fixVideoProfile } from "@/api/fixdata";
import VideoPlayer from "./components/VideoPlayer";

const defaultListQuery = {
  title: null,
  pageNum: 1,
  pageSize: 10,
  status: null,
  uvid: null,
  pid: null,
  uuid: null,
};
const defaultVideoOptions = {
  autoplay: true, //自动播放
  controls: true, //用户可以与之交互的控件
  loop: false, //视频一结束就重新开始
  muted: false, //默认情况下将使所有音频静音
  aspectRatio: "16:9", //显示比率
  preload: "auto",
  fullscreen: {
    options: { navigationUI: "hide" },
  },
  poster: null,
  sources: [],
};
export default {
  components: { VideoPlayer },
  name: "productList",
  data() {
    return {
      operates: [
        {
          label: "批量审核",
          value: "verify",
        },
        {
          label: "批量设置分区",
          value: "setPartition",
        },
      ],
      operateType: "verify",
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: true,
      selectPartitionValue: null,
      partitionOptions: [],
      statusTab: "-1",
      countMap: {
        allCount: 0,
        offTheShelfCount: 0,
        approvedCount: 0,
        reviewIssueCount: 0,
        issueReviewCount: 0,
        notPassedCount: 0,
      },
      viewVideoDialogVisible: false,
      videoOptions: Object.assign({}, defaultVideoOptions),
      verifyDialogVisible: false,
      verifyForm: {
        uvids: [],
        verifyStatus: 30,
        detail: "",
      },
      setPartitionDialogVisible: false,
      partitionForm: {
        uvids: [],
        pid: null,
        partitionName: null,
      },
      newPartitionValue: null,
      tip: null,
      multipleSelection: [],
      videoSrc: "",
    };
  },
  created() {
    this.getList();
    this.getPartitionList();
    this.getCountMap();
  },
  watch: {
    selectPartitionValue: function (newValue) {
      if (newValue != null) {
        this.listQuery.pid = newValue[newValue.length - 1];
      } else {
        this.listQuery.pid = null;
      }
    },
    newPartitionValue: function (newValue) {
      if (newValue != null) {
        // 二级分区
        this.partitionForm.pid = newValue[newValue.length - 1];
        let result = this.getPartitionNameAndTipById(this.partitionForm.pid);
        this.partitionForm.partitionName = result[0];
        this.tip = result[1];
      } else {
        this.partitionForm.pid = null;
        this.partitionForm.partitionName = null;
        this.tip = null;
      }
    },
  },
  filters: {
    statusFilter(value) {
      if (value === 40) {
        return "已下架";
      } else if (value === 30) {
        return "审核通过";
      } else if (value === 20) {
        return "待审核";
      } else if (value === 10) {
        return "待审核";
      } else {
        return "审核未通过";
      }
    },
  },
  methods: {
    getPartitionNameAndTipById(id) {
      let name = null;
      let tip = null;
      for (let i = 0; i < this.partitionOptions.length; i++) {
        if (this.partitionOptions[i].value == id) {
          name = this.partitionOptions[i].label;
          tip = this.partitionOptions[i].info;
          return [name, tip];
        }
        if (this.partitionOptions[i].children) {
          for (let j = 0; j < this.partitionOptions[i].children.length; j++) {
            if (this.partitionOptions[i].children[j].value == id) {
              name = this.partitionOptions[i].children[j].label;
              tip = this.partitionOptions[i].children[j].info;
              return [name, tip];
            }
            if (this.partitionOptions[i].children[j].children) {
              for (
                let k = 0;
                k < this.partitionOptions[i].children[j].children.length;
                k++
              ) {
                if (
                  this.partitionOptions[i].children[j].children[k].value == id
                ) {
                  name = this.partitionOptions[i].children[j].children[k].label;
                  tip = this.partitionOptions[i].children[j].children[k].info;
                  return [name, tip];
                }
              }
            }
          }
        }
      }
      return name;
    },
    isEmpty(str) {
      if (str === null || str === "" || str === undefined) {
        return true;
      } else {
        return false;
      }
    },
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then((response) => {
        this.listLoading = false;
        this.list = response.data.list;
        // console.log(this.list);
        this.total = response.data.total;
      });
    },
    getPartitionList() {
      fetchListWithChildren().then((response) => {
        let list = response.data;
        this.partitionOptions = [];
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              let cc = [];
              let item = list[i].children[j];
              if (item.children != null && item.children.length > 0) {
                for (let k = 0; k < item.children.length; k++) {
                  const element = item.children[k];
                  cc.push({
                    label: element.partitionName,
                    value: element.id,
                    info: element.info,
                  });
                }
              }
              children.push({
                label: list[i].children[j].partitionName,
                value: list[i].children[j].id,
                info: list[i].children[j].info,
                children: cc.length === 0 ? null : cc,
              });
            }
          }
          this.partitionOptions.push({
            label: list[i].partitionName,
            value: list[i].id,
            info: list[i].info,
            children: children.length === 0 ? null : children,
          });
        }
      });
    },
    getCountMap() {
      getCounts(this.listQuery).then((res) => {
        this.countMap = res.data;
      });
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.statusTab = "-1";
      // console.log(this.listQuery.pid);
      this.getList();
      this.getCountMap();
    },
    handleClickTabs(tab, event) {
      // console.log(this.statusTab);
      var status = Number(this.statusTab);
      if (status !== -1) {
        this.listQuery.status = status;
      } else {
        this.listQuery.status = null;
      }
      this.listQuery.pageNum = 1;
      this.getList();
      this.getCountMap();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
      this.getCountMap();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
      this.getCountMap();
    },
    handleResetSearch() {
      this.selectPartitionValue = [];
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleDelete(index, row) {
      this.$confirm("删除视频会删除视频相关数据，是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteVideo(row.uvid).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "删除成功",
              type: "success",
              duration: 1000,
            });
            this.getList();
            this.getCountMap();
          }
        });
      });
    },
    handleViewVideo(index, row) {
      this.videoSrc = row.url;
      this.viewVideoDialogVisible = true;
    },
    handleViewDialogClose() {
      this.viewVideoDialogVisible = false;
      this.videoSrc = "";
    },
    handleEdit(index, row) {
      let jumpRoute = this.$router.resolve({
        path: "/cms/updateVideo",
        query: { uvid: row.uvid },
      });
      window.open(jumpRoute.href, "_blank");
    },
    handleVerify(index, row) {
      this.verifyDialogVisible = true;
      this.verifyForm.uvids = [row.uvid];
    },
    handleVerifySubmit() {
      let params = new URLSearchParams();
      params.append("uvids", this.verifyForm.uvids);
      params.append("verifyStatus", this.verifyForm.verifyStatus);
      params.append("detail", this.verifyForm.detail);
      updateStatus(params).then((res) => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000,
        });
        this.verifyDialogVisible = false;
        this.getList();
        this.getCountMap();
      });
    },
    handleSetPartition(index, row) {
      this.partitionForm.uvids = [row.uvid];
      this.setPartitionDialogVisible = true;
    },
    handleSetPartitionSubmit() {
      console.log(this.partitionForm);
      if (this.partitionForm.pid && this.partitionForm.partitionName) {
        changePartition(this.partitionForm).then((res) => {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1000,
          });
          this.setPartitionDialogVisible = false;
          this.getList();
        });
      } else {
        this.$message({
          message: "请选择分区",
          type: "error",
          duration: 1000,
        });
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({
          message: "请选择操作类型",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: "请选择要操作的视频",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      let uvids = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        uvids.push(this.multipleSelection[i].uvid);
      }
      if (this.operateType === "verify") {
        this.verifyDialogVisible = true;
        this.verifyForm.uvids = uvids;
      } else if (this.operateType === "setPartition") {
        this.setPartitionDialogVisible = true;
        this.partitionForm.uvids = uvids;
      }
    },
    fixTime() {
      this.$message({
        message: "执行成功，后台需要一段时间执行该过程，请稍作等待",
        type: "success",
        duration: 1000,
      });
      fixVideoTime();
    },
    fixProfile() {
      this.$message({
        message: "执行成功，后台需要一段时间执行该过程，请稍作等待",
        type: "success",
        duration: 1000,
      });
      fixVideoProfile();
    },
    fixUvid() {
      this.$message({
        message: "执行成功，后台需要一段时间执行该过程，请稍作等待",
        type: "success",
        duration: 1000,
      });
      fixVideoUvid();
    },
  },
};
</script>
<style>
.success-status {
  background-color: #67c23a;
  color: white;
}
.error-status {
  background-color: #f56c6c;
  color: white;
}
</style>


